package com.ba.grain;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Iterator;

import junit.framework.Assert;
import util.FoodType;
import util.Grade;
import util.Quotation;
import util.Site;

public class ListItem extends Quotation implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public Site mSite;
	public FoodType mFoodType;
	public Grade mGrade;
	public String key;

	public String mFilePath;

	public Site getSite() {
		if (mSite != null) {
			return mSite;
		}
		Iterator<Site> it = G.sSites.iterator();
		while (it.hasNext()) {
			Site site = (Site) it.next();
			if (site.id == site_id) {
				mSite = site;
				return site;
			}
		}
		return null;
	}

	public FoodType getFood() {
		if (mFoodType != null) {
			return mFoodType;
		}
		Site site = getSite();
		if (site != null) {
			Iterator<FoodType> it = site.foods.iterator();
			while (it.hasNext()) {
				FoodType foodType = (FoodType) it.next();
				if (foodType.id == foodType_id) {
					mFoodType = foodType;
					return foodType;
				}
			}
		}
		return null;
	}

	public static ListItem fromString(String desc) {
		ListItem gi = new ListItem();
		String att_values = desc.substring(1, desc.length() - 1);
		String[] att_val = att_values.split(",");
		for (int i = 0; i < att_val.length; i++) {
			try {
				String[] pair = att_val[i].split("=");
				Field field = gi.getClass().getField(pair[0].trim());
				if ("int".equalsIgnoreCase(field.getType().toString())) {
					field.setInt(gi, Integer.parseInt(pair[1]));
				} else if ("float".equalsIgnoreCase(field.getType().toString())) {
					field.setFloat(gi, Float.parseFloat(pair[1]));
				} else if ("boolean".equalsIgnoreCase(field.getType().toString())) {
					field.setBoolean(gi, Boolean.parseBoolean(pair[1]));
				} else {
					field.set(gi, pair[1]);
				}
			} catch (Exception e) {
				e.printStackTrace();
				Assert.assertTrue(e.getMessage(), false);
			}
		}
		return gi;
	}

	public boolean isUploaded() {
		return mUploaded;
	}

}
